package archer.framework.utils;

import jodd.http.HttpMultiMap;
import jodd.http.HttpRequest;

import java.util.HashMap;
import java.util.Map;

/**
 * http请求工具类
 *
 * @author Kent
 * @date 2015/6/25
 */
public class HttpUtils {

    public static String post(String url) {
        return HttpRequest.post(url).charset("utf-8").send().bodyText();
    }

    public static String post(String url, Map queryMap) {
        return HttpRequest.post(url).form(queryMap).charset("utf-8").send().bodyText();
    }

    public static String get(String url) {
        return HttpRequest.get(url).charset("utf-8").send().bodyText();
    }

    public static String get(String url, String queryString) {
        return HttpRequest.get(url).queryString(queryString).charset("utf-8").send().bodyText();
    }

    public static String get(String url, Map queryMap) {
        return HttpRequest.get(url).query(queryMap).charset("utf-8").send().bodyText();
    }

    public static Map<String, Object[]> asParameterMap(HttpMultiMap<?> queryMap) {

        Map<String, Object[]> result = new HashMap<>();
        if (queryMap == null || queryMap.isEmpty()) {
            return null;
        }

        for (Map.Entry<String, ?> entry : queryMap) {
            String key = entry.getKey();

            Object value = entry.getValue();
            if (value == null) {
                result.put(key, null);
            } else {
                result.put(key, new Object[]{value});
            }

        }
        return result;
    }
}
